package com.forum.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.forum.common.Result;
import com.forum.dto.ChatRecordDto;
import com.forum.dto.ConversationDto;
import com.forum.dto.PrivateMessageRequest;
import com.forum.bean.Messages;
import com.forum.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 发起私信接口：
     * 1. 根据 currentUserId 和 targetUserId 查询双方聊天记录，条件为（sender_id=currentUserId AND receiver_id=targetUserId）
     *    OR (sender_id=targetUserId AND receiver_id=currentUserId)，按 create_at 降序排序，取最新一条。
     * 2. 如果存在，则返回该消息；否则，新建一条记录，内容默认“Hi~”，并返回该记录。
     */
    @Transactional
    public Result<Messages> initiatePrivateMessage(PrivateMessageRequest req) {
        try {
            QueryWrapper<Messages> wrapper = new QueryWrapper<>();
            // 构造双方聊天的条件
            wrapper.and(qw -> qw.eq("sender_id", req.getCurrentUserId())
                            .eq("receiver_id", req.getTargetUserId()))
                    .or(qw -> qw.eq("sender_id", req.getTargetUserId())
                            .eq("receiver_id", req.getCurrentUserId()));
            wrapper.orderByDesc("created_at");
            // 限制返回1条记录
            wrapper.last("LIMIT 1");

            List<Messages> list = messageMapper.selectList(wrapper);
            Messages message = new Messages();
            if (list == null || list.isEmpty()) {
                message.setContent("Hi~");
                // 存在聊天记录，返回最新的一条
            }else{
                message.setContent(req.getContent());
            }
            message.setSenderId(req.getCurrentUserId());
            message.setReceiverId(req.getTargetUserId());
            message.setCreatedAt(LocalDateTime.now());
            int rows = messageMapper.insert(message);
            if (rows != 1) {
                return Result.fail("新建私信记录失败");
            }
            return Result.ok(message);

        } catch (Exception e) {
            return Result.fail("发起私信异常：" + e.getMessage());
        }
    }

    public Result<List<ConversationDto>> getConversationList(Integer currentUserId) {
        try {
            List<ConversationDto> list = messageMapper.selectConversationList(currentUserId);
            return com.forum.common.Result.ok(list);
        } catch (Exception e) {
            return com.forum.common.Result.fail("查询私信列表异常：" + e.getMessage());
        }
    }



    /**
     * 删除当前用户与目标用户之间的所有私信记录
     * @param currentUserId 当前登录用户ID
     * @param targetUserId 目标用户ID
     * @return 统一的 Result 结构，成功时提示删除的记录数
     */
    @Transactional
    public Result<String> deleteConversation(Integer currentUserId, Integer targetUserId) {
        try {
            QueryWrapper<Messages> wrapper = new QueryWrapper<>();
            // 构造双方条件，需要注意 and/or 的结合
            wrapper.and(qw ->
                    qw.eq("sender_id", currentUserId).eq("receiver_id", targetUserId)
            ).or(qw ->
                    qw.eq("sender_id", targetUserId).eq("receiver_id", currentUserId)
            );
            int deletedCount = messageMapper.delete(wrapper);
            if (deletedCount > 0) {
                return Result.ok("删除私信成功，共删除 " + deletedCount + " 条记录");
            } else {
                return Result.fail("未找到双方私信记录");
            }
        } catch (Exception e) {
            return Result.fail("删除私信异常：" + e.getMessage());
        }
    }


    /**
     * 查询当前用户与目标用户之间的所有聊天记录
     * @param currentUserId 当前登录用户ID
     * @param targetUserId 目标用户ID
     * @return 返回查询到的聊天记录列表，封装在 Result 内部
     */
    public Result<List<ChatRecordDto>> getChatRecords(Integer currentUserId, Integer targetUserId) {
        try {
            List<ChatRecordDto> list = messageMapper.selectChatRecords(currentUserId, targetUserId);
            return com.forum.common.Result.ok(list);
        } catch (Exception e) {
            return com.forum.common.Result.fail("查询聊天记录异常：" + e.getMessage());
        }
    }

}
